package org.iartisan.wechatsdk

import org.iartisan.wechatsdk.common.res.WechatResError

import scala.reflect.{ClassTag, _}

/**
 *
 *
 * @author King  2019-7-26
 */
object Utils {

  //定义一个隐式转换类 json to obj
  implicit class ConvertJsonToObj(val json: String) {
    def toObject[T: ClassTag]: T = {
      WechatGsonBuilder.create.fromJson(json, classTag[T].runtimeClass)
    }
  }

  //定义一个隐式转换类 obj to json
  implicit class ConvertObjToJson(val obj: Any) {
    def toJson = WechatGsonBuilder.create.toJson(obj)
  }

  //定义一个隐式转换类 obj to json
  implicit class WechatParseEngine(val json: String) extends LogAspect {
    def toWechatObj[T: ClassTag]: T = {
      //先判断是否是error
      val error = Option(WechatGsonBuilder.create.fromJson(json, classOf[WechatResError]))
      error.getOrElse(new WechatResError).getErrcode match {
        case x if x != 0 =>
          log.error(s"返回码 errcode :${error.get.getErrcode} 错误信息:errmsg:${error.get.getErrcode}")
          throw new IllegalArgumentException(error.get.getErrcode + ":" + error.get.getErrmsg)
        case _ => WechatGsonBuilder.create.fromJson(json, classTag[T].runtimeClass)
      }

    }
  }

}


